<template>
	<scroll-view scroll-y="true" class="container" :class="themeStyle" v-if="addonIsExit.memberregister">
		<view class="header-wrap" :class="themeStyle">
			<view class="logo-box">
				<!-- <image src="../../../static/logo.png" mode="aspectFit"></image> -->
				<image :src="$util.img(infos.logo)" mode="aspectFit"></image>
				<text>注册</text>
			</view>
			<view class="to-login">
				<text>已有账号，立即</text><text class="login-text" @click="toLogin">登录</text>
			</view>
		</view>
		<view class="body-wrap">
			<view class="form-wrap reg-mar-btm">
				<view class="input-wrap" v-show="registerMode == 'account'">
					<!-- <text class="iconfont iconyonghu"></text> -->
					<view class="content"><input type="text" placeholder="请输入手机号" placeholder-class="input-placeholder" class="input"
						 v-model="formData.account" /></view>
				</view>
				<view class="input-wrap">
					<!-- <text class="iconfont iconLjianpanyanzhengma-"></text> -->
					<view class="content">
						<input type="text" placeholder="请输入手机验证码" placeholder-class="input-placeholder" class="input" v-model="formData.phonecode" />
						<!-- <text class="check-duanxin" type="default" @click="Getphonecode()">获取短信验证码</text> -->
						<view class="dynacode time-text" :class="dynacodeData.seconds == 120 ? 'ns-text-color' : 'ns-text-color-gray'"
						 @click="Getphonecode">
							{{ dynacodeData.codeText }}
						</view>
					</view>
				</view>
				<view class="input-wrap">
					<!-- <text class="iconfont iconmima"></text> -->
					<view class="content"><input type="password" placeholder="请输入登录密码" placeholder-class="input-placeholder" class="input"
						 v-model="formData.password" /></view>
				</view>
				<view class="input-wrap">
					<!-- <text class="iconfont iconmima"></text> -->
					<view class="content"><input type="text" v-model="formData.tuijiancode" :disabled="tuijiancode_option" placeholder="请输入推荐码(可选)"
						 placeholder-class="input-placeholder" class="input" @input="getInviteMember" />
						<text class="message">{{InviteMemberName}}</text>
					</view>
				</view>
			</view>
			<!-- <view class="forget-section">
				<view></view>
				<view class="align-right"><text @click="toLogin">已有账号，立即登录</text></view>
			</view> -->
			<button type="default" @click="register" class="login-btn">注册</button>
			<view class="regisiter-agreement">
				<text style="margin-right: 10rpx;border: 2rpx solid #cfcfcf;padding: 0rpx 14rpx;" v-model="is_zhucexieyi" @click="onxieyi" :class="is_zhucexieyi==true ? 'bg-red-5':''"></text> 请同意
				<text class="ns-text-color ns-font-size-sm" @click="openPopup('register')">《注册协议》</text>及<text class="ns-text-color ns-font-size-sm" @click="openPopup('privacy')">《隐私协议》</text>
			</view>
		</view>

			<uni-popup ref="registerPopup" type="bottom" class="wap-floating">
				<view style="border: 0;" class="flex-row margin-top-sm justify-center justify-between bg-gray-1 padding-sm border-bottom-xs border-gray-4 border-solid">
					<text class="text-xl color-red-6 text-bold">{{ agreement[agreementType].title }}</text>
				</view>
				
				<view class="padding-md bg-gray-1">
					<n-html :content="agreement[agreementType].content" style="height: 800rpx;overflow-y:scroll;"></n-html>
				</view>
			</uni-popup>

		<uni-popup ref="phone_Popup" type="center" class="phone-floating">
			<view class="phone-box">
				<image :src="captcha.img" class="phone-img" mode="aspectFit" @click="GetimgCode()" style="text-align: center;margin: 0 auto;display: block;margin-bottom: 10px;"></image>
				<view class="phonecode-box">
					<input type="text" v-model="phone_test" placeholder="请输入验证码" />
					<button type="default" class="test-btn" @click="sendMobileCode()">获取验证码</button>
				</view>
			</view>

		</uni-popup>
		
		<bind-mobile ref="bindMobile"></bind-mobile>
	</scroll-view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import validate from 'common/js/validate.js';
	import auth from 'common/js/auth.js';
	import bindMobile from '@/components/bind-mobile/bind-mobile.vue';

	export default {
		components: {
			uniPopup,
			bindMobile
		},
		data() {
			return {
				allowRegister: true, // 是否允许注册
				is_zhucexieyi: true,
				registerMode: 'account',
				formData: {
					mobile: '',
					account: '', //手机号
					password: '', //密码
					phonecode: '', //验证码
					tuijiancode: '', //推广码
					key: ''
				},
				tuijiancode_option: false,
				captcha: {
					img: '',
					id: ''
				},
				dynacodeData: {
					seconds: 120,
					timer: null,
					codeText: '获取动态码',
					isSend: false
				},
				phone_test: '', //获取验证码时的信息
				agreement:{
					register:{
						// 注册协议
						title: '',
						content: ''
					},
					privacy:{
						// 隐私协议
						title: '',
						content: ''
					},
				},
				agreementType:'register',
				isSub: false,
				back: '', // 返回页
				// logo图
				infos: {},
				InviteMemberName: ''
			};
		},
		mixins: [auth],
		onLoad(option) {
			if (option.back) this.back = option.back;
			if (option.invite_code) {
				this.formData.tuijiancode = option.invite_code;
				this.tuijiancode_option = true
			}
			if (uni.getStorageSync('authInfo')) {
				let data = uni.getStorageSync('authInfo');
				if (data.authInfo) this.authInfo = data.authInfo;
				if (data.userInfo) this.userInfo = data.userInfo;
			}
			if (option.mobile) {
				this.formData.account = option.mobile
			}
		},
		computed: {
			// 使用对象展开运算符将此对象混入到外部对象中
			themeStyle() {
				return 'theme-' + this.$store.state.index.themeStyle
			},
			addonIsExit() {
				return this.$store.state.index.addonIsExit
			}
		},
		onShow() {
			// 刷新多语言
			this.$langConfig.refresh();
			if (!this.addonIsExit.memberregister) {
				this.$util.showToast({
					title: '注册插件未安装',
					mask: true,
					duration: 2000
				})
				setTimeout(() => {
					this.$util.redirectTo('/pages/index/index/index', {}, 'redirectTo')
				}, 2000);
				return;
			}

			// #ifdef MP
			this.getCode();
			// #endif
			this.getRegisiterAggrement();
			this.getPrivacyAggrement();
			this.getRegisterConfig();
			this.getUserInfo();
			// 获取网站信息
			this.getInfo()
		},
		methods: {
			onxieyi(){
				this.is_zhucexieyi = !this.is_zhucexieyi
			},
			getInfo() {
				// 获取网站信息
				this.$api.sendRequest({
					url: '/api/website/info',
					success: res => {
						if (res.code == 0) {
							this.infos = res.data;

							// console.log('获取网站信息1' + this.infos.longitude);
							// console.log('获取网站信息2' + this.infos.latitude);
						}
					}
				});
			},
			getInviteMember() {
				if (this.formData.tuijiancode.length === 0) {
					this.InviteMemberName = ''
				} else {
					this.$api.sendRequest({
						url: '/api/member/getInviteMember',
						data: {
							invite_code:this.formData.tuijiancode
						},
						success: res => {
							if (res.code >= 0) {
								if(res.data != null && 
								typeof res.data === 'object' && Object.keys(res.data).length > 0){
									this.InviteMemberName = res.data.show_name;
								} else {
									this.InviteMemberName = '';
								}
								console.log(res);
							}
						}
					});
				}
			},

			/**
			 * 切换注册方式
			 */
			switchRegisterMode() {
				if (this.registerMode == 'mobile') {
					if (this.registerConfig.type.indexOf('plain') != -1) this.registerMode = 'account';
				} else if (this.registerMode == 'account') {
					if (this.registerConfig.type.indexOf('mobile') != -1) this.registerMode = 'mobile';
				}
			},
			/**
			 * 展示注册协议
			 */
			openPopup(agreementType) {
				this.agreementType = agreementType;
				if (this.agreement[agreementType].content != '') {
					this.$refs.registerPopup.open();
				}
			},
			/**
			 * 获取注册协议
			 */
			getRegisiterAggrement() {
				this.$api.sendRequest({
					url: '/api/register/aggrement',
					success: res => {
						if (res.code >= 0) {
							this.agreement.register = res.data;
						}
					}
				});
			},
			/**
			 * 获取隐私协议
			 */
			getPrivacyAggrement() {
				this.$api.sendRequest({
					url: '/api/config/agreement',
					data:{
						key : 'PRIVACY'
					},
					success: res => {
						if (res.code >= 0) {
							this.agreement.privacy = res.data;
						}
					}
				});
			},
			/**
			 * 获取注册配置
			 */
			getRegisterConfig() {
				this.$api.sendRequest({
					url: '/api/register/config',
					success: res => {
						if (res.code >= 0) {
							this.registerConfig = res.data.value;
							if (this.registerConfig.is_enable != 1) {
								this.$util.showToast({
									title: '平台未启用注册!',
									success: () => {
										setTimeout(() => {
											this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
										}, 1500);
									}
								});
							}
						}
					}
				});
			},
			/**
			 * 注册
			 */
			register() {
				var data = {
					// username: this.formData.account.trim(),
					password: this.formData.password,
				};
				
				
				
				if (Object.keys(this.authInfo).length) {
					data[this.authInfo.auth_tag] = this.authInfo.auth_openid;
				}
				if (this.userInfo.avatarUrl != '') data.headimg = this.userInfo.avatarUrl;
				if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member');
				//console.log(data)

				if (this.verify(data)) {
					if (this.isSub) return;
					this.isSub = true;
					data.mobile = this.formData.account
					data.key = this.formData.key
					data.code = this.formData.phonecode
					data.invite_code = this.formData.tuijiancode
					//console.log(data)
					this.$api.sendRequest({
						url: '/api/register/mobile',
						data,
						success: res => {
							if (res.code >= 0) {
								console.log(res)
								uni.setStorage({
									key: 'token',
									data: res.data.token,
									success: () => {
										uni.removeStorageSync('loginLock');
										uni.removeStorageSync('unbound');
										uni.removeStorageSync('authInfo');
										if (this.back != '') {
											this.$util.redirectTo(this.back, {}, 'reLaunch');
										} else {
											this.$util.redirectTo('/pages/member/index/index', {}, 'reLaunch');
										}
									}
								});
							} else {
								this.isSub = false;
								this.$util.showToast({
									title: res.message
								});
							}
						},
						fail: res => {
							this.isSub = false;
						}
					});
				}
			},
			verify(data) {
				if(!this.is_zhucexieyi){
					uni.showToast({
						icon: 'none',
						title: '必须同意注册协议后继续注册！'
					});
					return
				}
				
				let rule = [{
						name: 'password',
						checkType: 'required',
						errorMsg: '请输入登录密码'
					}],
					regConfig = this.registerConfig;
				//console.log(this.registerConfig)
				// 密码长度
				if (regConfig.pwd_len > 0) {
					rule.push({
						name: 'password',
						checkType: 'lengthMin',
						checkRule: regConfig.pwd_len,
						errorMsg: '密码长度不能小于' + regConfig.pwd_len + '位'
					});
				}
				// 密码设定要求
				if (regConfig.pwd_complexity != '') {
					let passwordErrorMsg = '密码需包含',
						reg = '';
					if (regConfig.pwd_complexity.indexOf('number') != -1) {
						reg += '(?=.*?[0-9])';
						passwordErrorMsg += '数字';
					}
					if (regConfig.pwd_complexity.indexOf('letter') != -1) {
						reg += '(?=.*?[a-z])';
						passwordErrorMsg += '、小写字母';
					}
					if (regConfig.pwd_complexity.indexOf('upper_case') != -1) {
						reg += '(?=.*?[A-Z])';
						passwordErrorMsg += '、大写字母';
					}
					if (regConfig.pwd_complexity.indexOf('symbol') != -1) {
						reg += '(?=.*?[#?!@$%^&*-])';
						passwordErrorMsg += '、特殊字符';
					}
					rule.push({
						name: 'password',
						checkType: 'reg',
						checkRule: reg,
						errorMsg: passwordErrorMsg
					});
				}
				var checkRes = validate.check(data, rule);
				// 验证密码
				if (checkRes) {
					// 验证手机号
					let reg_tel = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
					if (reg_tel.test(this.formData.account.trim())) {
						console.log('通过')
						return true
					} else {
						uni.showToast({
							title: '请输入正确的手机号'
						})
						return false
					}
				} else {
					this.$util.showToast({
						title: validate.error
					});
					return false;
				}
			},
			Getphonecode() {
				let reg_tel = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
				if (reg_tel.test(this.formData.account.trim())) {
					if (this.dynacodeData.codeText == '获取动态码') {
						this.$refs.phone_Popup.open()
						// 开始倒计时
						this.GetimgCode()
					} else {
						uni.showToast({
							title: this.dynacodeData.codeText,
							icon: 'none'
						})
					}

				} else {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
				}

			},
			// 获取图片验证码
			GetimgCode() {
				console.log(54612)
				this.$api.sendRequest({
					url: '/api/captcha/captcha',
					data: {
						captcha_id: ''
					},
					success: res => {
						console.log(res)
						if (res.code >= 0) {
							this.captcha = res.data;
							this.captcha.img = this.captcha.img.replace(/\r\n/g, '');
						}
					}
				});

			},
			/**
			 * 发送手机动态码
			 */
			sendMobileCode() {
				if (this.dynacodeData.seconds != 120) return;
				if (this.dynacodeData.isSend) return;
				if (this.phone_test == '') {
					uni.showToast({
						title: '请输入图示的验证码',
						icon: 'none'
					})
					return
				}
				this.dynacodeData.isSend = true;
				this.$api.sendRequest({
					url: '/api/register/mobileCode',
					data: {
						captcha_id: this.captcha.id,
						captcha_code: this.phone_test,
						mobile: this.formData.account
					},
					success: res => {
						console.log(res)
						this.dynacodeData.isSend = false;
						if (res.code >= 0) {
							this.$refs.phone_Popup.close()
							this.formData.key = res.data.key;
							if (this.dynacodeData.seconds == 120 && this.dynacodeData.timer == null) {
								this.dynacodeData.timer = setInterval(() => {
									this.dynacodeData.seconds--;
									this.dynacodeData.codeText = this.dynacodeData.seconds + 's后可重新获取';
								}, 1000);
							}
						} else {
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: (err) => {
						this.$util.showToast({
							title: 'request:fail'
						});
						this.dynacodeData.isSend = false;
					}
				});
			},

			/**
			 * 去登录
			 */
			toLogin() {
				if (this.back) this.$util.redirectTo('/pages/login/login/login', {
					back: this.back
				});
				else this.$util.redirectTo('/pages/login/login/login');
			}
		},
		watch: {
			'dynacodeData.seconds': {
				handler(newValue, oldValue) {
					if (newValue == 0) {
						clearInterval(this.dynacodeData.timer);
						this.dynacodeData = {
							seconds: 120,
							timer: null,
							codeText: '获取动态码',
							isSend: false
						};
					}
				},
				immediate: true,
				deep: true
			}
		}
	};
</script>

<style lang="scss">
	@import '../public/css/common.scss';


	.phone-floating {
		/deep/ .uni-popup__wrapper.uni-custom.center .uni-popup__wrapper-box {
			border-radius: 10rpx;
		}

		.phone-box {
			width: 400rpx;
			padding: 20rpx;

			.phone-img {
				height: 80rpx;
				width: 200rpx;
				// width: 50rpx;
			}

			.phonecode-box {

				input {
					height: 70rpx;
					background-color: #f8f8f8;
					letter-spacing: 3rpx;
					width: 100%;
					text-align: center;
					font-size: 28rpx;
				}

				.test-btn {
					margin: 0;
					color: white;
					width: 100%;
					border-radius: 4rpx;
					height: 80rpx;
					margin-top: 20rpx;
					background-color: #FF335C;
				}
			}
		}

	}
</style>
